# -*- coding: utf-8 -*-
# @Time    : 2025/10/9
# @Author  : Qwen
# @File    : gaode_map_service.py
# @Describe: 高德地图路线规划服务

import requests
import json
import logging
from typing import Dict, Any
from luck.core.LuckConstant import LuckConstant

class MapSdkGaodeService:
    """高德地图服务实现"""
    
    def __init__(self, ak: str):
        # 高德地图API配置
        self.ak = ak
        self.base_url = "https://restapi.amap.com"
    
    def get_route_info(self, origin: str, destination: str, route_type: str = "driving", tactics: str = "0") -> Dict[str, Any]:
        """
        获取路线规划信息
        
        Args:
            origin: 起点坐标 (纬度,经度)
            destination: 终点坐标 (纬度,经度)
            route_type: 路线类型 (driving, walking, riding)
            tactics: 路线偏好 (使用高德地图strategy参数值)
            
        Returns:
            dict: 路线信息
        """
        try:
            # 转换坐标格式：前端传递的是纬度,经度，高德地图需要经度,纬度
            origin_parts = origin.split(',')
            destination_parts = destination.split(',')
            
            if len(origin_parts) != 2 or len(destination_parts) != 2:
                return {
                    "code": LuckConstant.CODE_FAIL,
                    "msg": "坐标格式错误，请使用纬度,经度格式"
                }
            
            # 转换为高德地图需要的经度,纬度格式
            gaode_origin = f"{origin_parts[1]},{origin_parts[0]}"
            gaode_destination = f"{destination_parts[1]},{destination_parts[0]}"
            
            # 根据路线类型选择API接口
            if route_type == "driving":
                api_url = f"{self.base_url}/v5/direction/driving"
                params = {
                    "origin": gaode_origin,
                    "destination": gaode_destination,
                    "key": self.ak,
                    "extensions": "all",  # 返回详细信息
                    "strategy": tactics,  # 添加路线偏好参数
                    "show_fields": "cost,tmcs,navi,cities,polyline,elocation,distance,duration,restriction,traffic_lights",  # 显示预计耗时、道路收费、红绿灯等字段
                    "output": "json",  # 输出格式
                    "ferry": "1",  # 是否使用轮渡
                    "plate": "",  # 车牌号（可选）
                    "cartype": "0"  # 车辆类型：0-小型车，1-货车
                }
            elif route_type == "walking":
                api_url = f"{self.base_url}/v5/direction/walking"
                params = {
                    "origin": gaode_origin,
                    "destination": gaode_destination,
                    "key": self.ak
                }
            elif route_type == "riding":
                api_url = f"{self.base_url}/v5/direction/bicycling"
                params = {
                    "origin": gaode_origin,
                    "destination": gaode_destination,
                    "key": self.ak
                }
            else:
                logging.warning(f"不支持的路线类型: {route_type}")
                return {
                    "code": LuckConstant.CODE_FAIL,
                    "msg": "不支持的路线类型"
                }
            
            logging.info(f"请求高德地图API: {api_url}, 参数: {params}")
            
            # 发送请求，添加请求头并处理SSL验证问题
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
            }
            
            # 发送请求，禁用SSL验证以解决连接问题
            try:
                response = requests.get(api_url, params=params, headers=headers, timeout=10, verify=False)
            except requests.exceptions.SSLError as ssl_error:
                # 如果SSL错误，尝试不使用代理
                response = requests.get(api_url, params=params, headers=headers, timeout=10, verify=False, proxies={})
            
            if response.status_code == 200:
                result = response.json()
                logging.info(f"高德地图API响应状态: {result.get('status')}")
                
                # 检查高德地图API返回状态
                if str(result.get("status")) == "1":  # 高德地图API返回的是字符串"1"
                    # 确保返回的数据包含必要的字段
                    if "route" in result:
                        route = result["route"]
                        if "paths" in route and len(route["paths"]) > 0:
                            # 处理每个路径的数据，添加v5新字段支持
                            for path in route["paths"]:
                                # 确保路径包含基本信息
                                if "distance" not in path:
                                    path["distance"] = "0"
                                if "duration" not in path:
                                    path["duration"] = "0"
                                
                                # 添加v5新字段的默认值
                                if "cost" not in path:
                                    path["cost"] = {"tolls": "0", "toll_distance": "0", "traffic_lights": "0"}
                                
                                # 处理每个步骤的详细信息
                                if "steps" in path:
                                    for step in path["steps"]:
                                        # 确保每个步骤都有必要的信息
                                        if "instruction" not in step:
                                            step["instruction"] = "未知路段"
                                        if "distance" not in step:
                                            step["distance"] = "0"
                                        if "duration" not in step:
                                            step["duration"] = "0"
                                        
                                        # 添加v5新字段支持
                                        if "cost" not in step:
                                            step["cost"] = {"tolls": "0", "toll_distance": "0"}
                                        if "traffic_lights" not in step:
                                            step["traffic_lights"] = "0"
                    
                    return {
                        "code": LuckConstant.CODE_SUCCESS,
                        "msg": LuckConstant.MSG_SUCCESS,
                        "data": result
                    }
                else:
                    error_msg = f"高德地图API错误: {result.get('info', '未知错误')}"
                    logging.error(error_msg)
                    return {
                        "code": LuckConstant.CODE_FAIL,
                        "msg": error_msg
                    }
            else:
                error_msg = f"请求失败，状态码: {response.status_code}"
                logging.error(error_msg)
                return {
                    "code": LuckConstant.CODE_FAIL,
                    "msg": error_msg
                }
                
        except requests.exceptions.Timeout:
            error_msg = "请求高德地图API超时"
            logging.error(error_msg)
            return {
                "code": LuckConstant.CODE_FAIL,
                "msg": error_msg
            }
        except requests.exceptions.RequestException as e:
            error_msg = f"网络请求错误: {str(e)}"
            logging.error(error_msg)
            return {
                "code": LuckConstant.CODE_FAIL,
                "msg": error_msg
            }
        except Exception as e:
            error_msg = f"服务处理错误: {str(e)}"
            logging.error(error_msg)
            return {
                "code": LuckConstant.CODE_FAIL,
                "msg": error_msg
            }